</div> <!-- .page-container closed -->

<!-- 底部导航栏 -->
<nav class="bottom-nav">
    <a href="index.php" class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'index.php' ? 'active' : ''; ?>"><i class="bi bi-house-door-fill"></i><span>首页</span></a>
    <a href="oder.php" class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'oder.php' ? 'active' : ''; ?>"><i class="bi bi-file-text-fill"></i><span>订单</span></a>
    <a href="agent.php" class="nav-item <?php echo in_array(basename($_SERVER['PHP_SELF']), ['seo.php', 'agent.php']) ? 'active' : ''; ?>"><i class="bi bi-megaphone-fill"></i><span>推广</span></a>
    <a href="profile.php" class="nav-item <?php echo in_array(basename($_SERVER['PHP_SELF']), ['profile.php', 'commission.php', 'rename.php']) ? 'active' : ''; ?>"><i class="bi bi-person-fill"></i><span>我的</span></a>
</nav>

<!-- JS引入 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vant@2.12/lib/vant.min.js"></script>

<script>
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(() => {
            if (typeof vant !== 'undefined') { vant.Toast.success('已复制!'); } 
            else { alert('已复制!'); }
        });
    }

    function handleAjaxError(xhr) {
        if(xhr.status === 401) {
            alert('登录已过期，请重新登录！');
            localStorage.removeItem('agent_token');
            window.location.href = './login.html';
        } else if(xhr.status === 403) {
            try {
                const res = JSON.parse(xhr.responseText);
                alert(res.msg);
            } catch(e) {
                alert('您需要完成实名认证才能继续操作。');
            }
            window.location.href = './rename.php';
        } else {
            alert('请求失败，请检查网络或联系管理员。');
        }
    }

    $(function() {
        const token = localStorage.getItem('agent_token');
        if (!token && window.location.pathname.indexOf('login.html') === -1 && window.location.pathname.indexOf('register.html') === -1) {
            alert('您尚未登录!');
            window.location.href = './login.html';
            return;
        }

        // 首页逻辑
        if ($('#dashboard-app').length > 0) {
            new Vue({
                el: '#dashboard-app',
                data: { stats: {} },
                created() { this.fetchDashboardData(); },
                methods: {
                    fetchDashboardData() {
                        $.ajax({
                            url: 'dashboard_data.php', type: 'GET', dataType: 'json',
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => { if (res.status === 0) this.stats = res.data; else alert(res.msg); },
                            error: handleAjaxError
                        });
                    }
                }
            });
        }
        
        // 订单页逻辑
        if ($('#order-list-container').length > 0) {
            function getOrderStatus(status) {
                const statuses = { '0':{t:'待审核',c:'warning'}, '1':{t:'已下单',c:'info'}, '2':{t:'已发货',c:'primary'}, '3':{t:'已完成',c:'success'}, '4':{t:'开卡失败',c:'danger'} };
                const s = statuses[status] || {t:'未知',c:'secondary'};
                return `<span class="badge bg-${s.c}">${s.t}</span>`;
            }
            function getCardStatus(status) { return status === '1' ? '<span class="badge bg-success">已激活</span>' : '<span class="badge bg-secondary">未激活</span>'; }
            function loadOrders() {
                const container = $('#order-list-container');
                const keyword = $('#filter-form input[name="keyword"]').val();
                const scope = $('#scope-switch').is(':checked') ? 'all' : 'self';
                container.html(`<div class="text-center p-5"><div class="spinner-border text-primary" role="status"></div></div>`);
                $.ajax({
                    url: 'oder_data.php', type: 'POST', dataType: 'json', data: { keyword: keyword, scope: scope },
                    beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                    success: function(res) {
                        container.empty();
                        if (res && res.status === 0 && Array.isArray(res.data)) {
                            if (res.data.length > 0) {
                                $.each(res.data, function(index, order) {
                                    let agentInfoHtml = (scope === 'all') ? `<div class="order-info-item"><span class="label">所属代理:</span><span class="value text-primary fw-bold">${order.agent_name}</span></div>` : '';
                                    const cardHtml = `<div class="card order-card mb-2">
                                        <div class="order-card-header"><h5>${order.goods_name}</h5><button class="btn btn-outline-primary btn-sm view-details-btn" data-index="${index}">查看详情</button></div>
                                        <div class="order-card-body">
                                            <div class="order-info-item"><span class="label">订单号:</span><span class="value">${order.order_id} <i class="bi bi-clipboard ms-1 text-muted" style="cursor: pointer;" onclick="copyToClipboard('${order.order_id}')"></i></span></div>
                                            <div class="order-info-item"><span class="label">收件人:</span><span class="value">${order.name}</span></div>
                                            ${agentInfoHtml}
                                            <div class="order-info-item"><span class="label">订单状态:</span><span class="value">${getOrderStatus(order.order_sta)}</span></div>
                                            <div class="order-info-item"><span class="label">激活状态:</span><span class="value">${getCardStatus(order.card_sta)}</span></div>
                                        </div></div>`;
                                    container.append(cardHtml);
                                });
                                container.data('orders', res.data);
                            } else { container.html('<div class="text-center p-5 text-muted">暂无订单数据</div>'); }
                        } else if (res && res.status === -10) {
                             container.html('<div class="text-center p-5 text-warning">请先完成实名认证</div>');
                             new bootstrap.Modal(document.getElementById('renameModal')).show();
                        } else { container.html(`<div class="text-center p-5 text-danger">${res.msg || '加载失败'}</div>`); }
                    },
                    error: handleAjaxError
                });
            }
            loadOrders();
            $('#filter-form').off('submit').on('submit', (e) => { e.preventDefault(); loadOrders(); });
            $('#scope-switch').off('change').on('change', loadOrders);
            $('#order-list-container').off('click', '.view-details-btn').on('click', '.view-details-btn', function() {
                const orderData = $('#order-list-container').data('orders')[$(this).data('index')];
                const modalBodyHtml = `<p><strong>套餐名称:</strong> <span>${orderData.goods_name}</span></p><hr class="my-2">
                    <p><strong>所属代理:</strong> <span>${orderData.agent_name}</span></p>
                    <p><strong>订单号:</strong> <span>${orderData.order_id} <i class="bi bi-clipboard" style="cursor: pointer;" onclick="copyToClipboard('${orderData.order_id}')"></i></span></p>
                    <p><strong>下单时间:</strong> <span>${orderData.order_time}</span></p><hr class="my-2">
                    <p><strong>收件人:</strong> <span>${orderData.name}</span></p><p><strong>联系电话:</strong> <span>${orderData.phone}</span></p>
                    <p><strong>身份证号:</strong> <span>${orderData.id_card}</span></p><p><strong>收货地址:</strong> <span>${orderData.address}</span></p><hr class="my-2">
                    <p><strong>订单状态:</strong> <span>${getOrderStatus(orderData.order_sta)}</span></p><p><strong>激活状态:</strong> <span>${getCardStatus(orderData.card_sta)}</span></p>
                    <p><strong>备注:</strong> <span>${orderData.notes || '-'}</span></p><p><strong>物流单号:</strong> <span>${orderData.logistics_id || '-'}</span></p>`;
                $('#orderDetailModalBody').html(modalBodyHtml);
                new bootstrap.Modal(document.getElementById('orderDetailModal')).show();
            });
        }

        // 代理管理页逻辑
        if ($('#agent-app').length > 0) {
            new Vue({
                el: '#agent-app',
                data: { keyword: '', isLoading: true, agents: [], stats: { total_agents: 0, active_agents: 0, recruitment_link: '' } },
                created() { this.loadAgents(); },
                methods: {
                    loadAgents() {
                        this.isLoading = true;
                        $.ajax({
                            url: 'agent_data.php', type: 'POST', dataType: 'json', data: { keyword: this.keyword },
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => {
                                if (res && res.status === 0) { this.agents = res.data.list; this.stats = res.data.stats; } 
                                else { alert(res.msg || '加载数据失败'); }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isLoading = false; }
                        });
                    },
                    copyLink() { copyToClipboard(this.stats.recruitment_link); }
                }
            });
        }
        
        // 个人中心页逻辑
        if ($('#profile-app').length > 0) {
            new Vue({
                el: '#profile-app',
                data: { profile: {} },
                created() { this.fetchProfileData(); },
                methods: {
                    fetchProfileData() {
                        $.ajax({
                            url: 'profile_data.php', type: 'GET', dataType: 'json',
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => { if (res.status === 0) this.profile = res.data; else alert(res.msg); },
                            error: handleAjaxError
                        });
                    },
                    logout() {
                        if (confirm('您确定要退出登录吗？')) {
                            localStorage.removeItem('agent_token');
                            window.location.href = './login.html';
                        }
                    }
                }
            });
        }
        
        // 佣金设置页逻辑
  if ($('#commission-app').length > 0) {
            new Vue({
                el: '#commission-app',
                data: {
                    isLoading: true,
                    isSubmitting: false,
                    form: {
                        type: 0,
                        value: 0.00
                    }
                },
                created() {
                    this.fetchCurrentCommission();
                },
                methods: {
                    fetchCurrentCommission() {
                        this.isLoading = true;
                        const token = localStorage.getItem('agent_token');
                        $.ajax({
                            url: 'commission_data.php', // 【核心修正】请求新的专用接口
                            type: 'GET',
                            dataType: 'json',
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => {
                                if (res.status === 0 && res.data) {
                                    this.form.type = res.data.type;
                                    this.form.value = res.data.value;
                                } else {
                                    alert(res.msg || '获取当前设置失败');
                                }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isLoading = false; }
                        });
                    },
                    saveCommission() {
                        this.isSubmitting = true;
                        const token = localStorage.getItem('agent_token');
                        $.ajax({
                            url: 'do_set_commission.php',
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                commission_type: this.form.type,
                                commission_value: this.form.value
                            },
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => {
                                const alertType = res.status === 0 ? 'success' : 'danger';
                                $('#alert-container').html(`<div class="alert alert-${alertType}">${res.msg}</div>`);
                            },
                            error: handleAjaxError,
                            complete: () => { this.isSubmitting = false; }
                        });
                    }
                }
            });
        }

        // 实名认证页逻辑
        if ($('#rename-app').length > 0) {
            new Vue({
                el: '#rename-app',
                data: {
                    isRenamed: false, // 默认为未实名
                    isLoading: true,
                    isSubmitting: false,
                    countdown: 0,
                    form: { name: '', uid: '', phone: '', code: '' }
                },
                created() {
                    // 页面加载时，先从个人信息接口获取实名状态
                    this.checkRenameStatus();
                },
                methods: {
                    checkRenameStatus() {
                        $.ajax({
                            url: 'profile_data.php', type: 'GET', dataType: 'json',
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => {
                                if (res.status === 0 && res.data) {
                                    this.isRenamed = res.data.is_renamed;
                                }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isLoading = false; }
                        });
                    },
                    getSmsCode() {
                        if (!/^1[3-9]\d{9}$/.test(this.form.phone)) { alert("请输入正确的手机号"); return; }
                        if (this.countdown > 0) return;

                        this.countdown = 60;
                        const timer = setInterval(() => {
                            this.countdown--;
                            if (this.countdown <= 0) { clearInterval(timer); }
                        }, 1000);

                        $.ajax({
                            url: 'send_sms_handler.php', type: 'POST', dataType: 'json',
                            data: { phoneNumber: this.form.phone },
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => { alert(res.msg); },
                            error: () => { alert('请求短信接口失败！'); }
                        });
                    },
                    submitRename() {
                        this.isSubmitting = true;
                        $.ajax({
                            url: 'do_rename.php', type: 'POST', dataType: 'json',
                            data: {
                                proxy_rename: this.form.name,
                                proxy_uid: this.form.uid,
                                proxy_phone: this.form.phone,
                                verification_code: this.form.code
                            },
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + token),
                            success: (res) => {
                                $('#alert-container-rename').html(`<div class="alert alert-${res.status === 0 ? 'success' : 'danger'}">${res.msg}</div>`);
                                if (res.status === 0) {
                                    setTimeout(() => { window.location.href = 'profile.php'; }, 1500);
                                }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isSubmitting = false; }
                        });
                    }
                }
            });
        }
         if ($('#account-app').length > 0) {
            new Vue({
                el: '#account-app',
                data: { isLoading: true, isSubmitting: false, account: {}, modal: { type: '', title: '' }, form: {}, modalInstance: null },
                created() { this.fetchAccountData(); },
                methods: {
                    fetchAccountData() {
                        this.isLoading = true;
                        $.ajax({
                            url: 'account_data.php', type: 'GET', dataType: 'json',
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('agent_token')),
                            success: (res) => { if (res.status === 0) this.account = res.data; },
                            error: handleAjaxError,
                            complete: () => { this.isLoading = false; }
                        });
                    },
                    openModal(type) {
                        this.modal.type = type;
                        if (type === 'alipay') {
                            this.modal.title = '绑定/修改支付宝';
                            this.form = { alipay_name: this.account.alipay_name, alipay_acc: this.account.alipay_acc };
                        } else if (type === 'bank') {
                            this.modal.title = '绑定/修改银行卡';
                            this.form = { ...this.account.bank_card }; 
                        }
                        if (!this.modalInstance) { this.modalInstance = new bootstrap.Modal(document.getElementById('editAccountModal')); }
                        this.modalInstance.show();
                    },
                    saveAccount() {
                        this.isSubmitting = true;
                        let formData = { type: this.modal.type, ...this.form };
                        $.ajax({
                            url: 'do_set_account.php', type: 'POST', dataType: 'json', data: formData,
                            beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('agent_token')),
                            success: (res) => {
                                $('#alert-container-main').html(`<div class="alert alert-${res.status === 0 ? 'success' : 'danger'}">${res.msg}</div>`);
                                if (res.status === 0) {
                                    this.modalInstance.hide();
                                    this.fetchAccountData();
                                }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isSubmitting = false; }
                        });
                    }
                }
            });
        }
         if ($('#password-app').length > 0) {
            new Vue({
                el: '#password-app',
                data: {
                    isSubmitting: false,
                    form: {
                        old_password: '',
                        new_password: '',
                        confirm_password: ''
                    }
                },
                methods: {
                    changePassword() {
                        if (this.form.new_password !== this.form.confirm_password) {
                            $('#alert-container-password').html(`<div class="alert alert-danger">两次输入的新密码不一致！</div>`);
                            return;
                        }
                        this.isSubmitting = true;
                        $.ajax({
                            url: 'do_change_password.php',
                            type: 'POST',
                            dataType: 'json',
                            data: this.form,
                            beforeSend: (xhr) => {
                                const token = localStorage.getItem('agent_token');
                                if (token) { xhr.setRequestHeader('Authorization', 'Bearer ' + token); }
                                else { window.location.href = './login.html'; }
                            },
                            success: (res) => {
                                const alertType = res.status === 0 ? 'success' : 'danger';
                                $('#alert-container-password').html(`<div class="alert alert-${alertType}">${res.msg}</div>`);
                                if (res.status === 0) {
                                    localStorage.removeItem('agent_token'); // 强制用户重新登录
                                    setTimeout(() => { window.location.href = 'login.html'; }, 2000);
                                }
                            },
                            error: handleAjaxError,
                            complete: () => { this.isSubmitting = false; }
                        });
                    }
                }
            });
        }
    });
</script>
</body>
</html>